package com.sskj.fabi.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.common.base.App;
import com.sskj.common.util.CheckUtil;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.ImgUtil;
import com.sskj.common.util.PermissionTipUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.ui.activity.OrderRecordDetailActivity;
import com.sskj.lib.bean.FabiBuySellEnum;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.util.CoinUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.math.BigDecimal;
import java.util.ArrayList;

public class TipFabiUtil {

    private static boolean isPrice;
    private static String resultNum;
    private static String resultRMB;

    public static BottomSheetDialog showTrade(Activity activity, boolean isBuy, String price, String minLimit, String maxLimit, String leftNum, OnInputList onInputList) {

        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(activity);
        View rootView = LayoutInflater.from(activity).inflate(R.layout.fabi_bottom_sheet_trade, null, false);
        TextView tvTitle = rootView.findViewById(R.id.tvTitle);
        TextView tvPrice = rootView.findViewById(R.id.tvPrice);
        CommonTabLayout commonTabLayout = rootView.findViewById(R.id.commonTabLayout);
        EditText etNum = rootView.findViewById(R.id.etNum);
        EditText etPwd = rootView.findViewById(R.id.etPwd);
        TextView tvUnit = rootView.findViewById(R.id.tvUnit);
        TextView tvAll = rootView.findViewById(R.id.tvAll);
        TextView tvUSDT = rootView.findViewById(R.id.tvUSDT);
        TextView tvRMB = rootView.findViewById(R.id.tvRMB);
        TextView tvLimitMoney = rootView.findViewById(R.id.tvLimitMoney);
        Button btOrder = rootView.findViewById(R.id.btOrder);
        isPrice = false;
        tvAll.setText(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil1_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        tvTitle.setText(String.format("%sUSDT", isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        tvPrice.setText(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil2_h), CoinUtil.keepRMB(price)));
        etNum.setHint(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil3_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle(), isPrice ? App.INSTANCE.getString(R.string.fabi_tipFabiUtil4_h) : App.INSTANCE.getString(R.string.fabi_buySellBean2_h)));
        tvLimitMoney.setText(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil6_h), CoinUtil.keepRMB(minLimit), CoinUtil.keepRMB(maxLimit)));
        tvUnit.setText(isPrice ? "CNY" : "USDT");
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil7_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()), 0, 0));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.fabi_tipFabiUtil8_h), 0, 0));
        commonTabLayout.setTabData(tabItems);
        resultNum = "0";
        resultRMB = "0";
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                etNum.setText("");
                if (position == 1 && !isPrice) {
                    isPrice = true;
                    etNum.setHint(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil9_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
                    tvUnit.setText("CNY");
                } else if (position == 0 && isPrice) {
                    isPrice = false;
                    etNum.setHint(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil10_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
                    tvUnit.setText("USDT");
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        ClickUtil.click(tvAll, () -> {
            String num = calculateAll(isPrice, price, leftNum, maxLimit);
            etNum.setText(num);

        });
        RxTextView.afterTextChangeEvents(etNum)
                .subscribe(textEdit -> {
                    String text = textEdit.editable().toString();
                    if (!TextUtils.isEmpty(text)) {
                        if (isPrice) {
                            BigDecimal usdtBig = new BigDecimal(text).divide(new BigDecimal(price), 8, BigDecimal.ROUND_DOWN);
                            String usdt = CoinUtil.keepUSDT(usdtBig.toPlainString());
                            tvUSDT.setText(String.format("%s USDT", CoinUtil.keepUSDT(usdt)));
                            resultNum = usdt;
                            tvRMB.setText(String.format("￥%s", CoinUtil.keepRMB(text)));
                            resultRMB = text;
                        } else {
                            BigDecimal priceBig = new BigDecimal(text).multiply(new BigDecimal(price));
                            String rmb = CoinUtil.keepRMB(priceBig.toPlainString());
                            resultNum = text;
                            tvUSDT.setText(String.format("%s USDT", CoinUtil.keepUSDT(text)));
                            tvRMB.setText(String.format("￥%s", CoinUtil.keepRMB(rmb)));
                            resultRMB = rmb;
                        }
                    } else {
                        resultNum = "0";
                        tvUSDT.setText("0 USDT");
                        tvRMB.setText("￥0.00");
                    }
                });
        ClickUtil.click(btOrder, () -> {
            if (TextUtils.isEmpty(etNum.getText())) {
                ToastUtil.showShort(etNum.getHint());
                return;
            }
            if (Double.valueOf(resultRMB) > Double.valueOf(maxLimit)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil11_h));
                return;
            }
            if (Double.valueOf(resultRMB) < Double.valueOf(minLimit)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil12_h));
                return;
            }
            if (Double.valueOf(resultNum) > Double.valueOf(leftNum)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil13_h));
                return;
            }
            if (TextUtils.isEmpty(etPwd.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil14_h));
                return;
            }
            if (onInputList != null) {
                onInputList.onSure(resultNum, resultRMB, etPwd.getText().toString());
            }

        });

        bottomSheetDialog.setContentView(rootView);
        bottomSheetDialog.setCancelable(true);
        bottomSheetDialog.setCanceledOnTouchOutside(true);
        return bottomSheetDialog;

    }

    public static MaterialDialog showPublish(Context context, boolean isBuy, String price, String num, OnInputList onInputList) {
        MaterialDialog dialog = new MaterialDialog.Builder(context)
                .customView(R.layout.fabi_dialog_publish_confirm, false)
                .autoDismiss(false)
                .cancelable(false)
                .show();
        View view = dialog.getCustomView();
        ((ViewGroup) (view.getParent())).setBackgroundColor(Color.TRANSPARENT);
        ((ViewGroup) (view.getParent().getParent())).setBackgroundColor(Color.TRANSPARENT);
        ((ViewGroup) (view.getParent().getParent().getParent())).setBackgroundColor(Color.TRANSPARENT);
        ((ViewGroup) (view.getParent().getParent().getParent().getParent())).setBackgroundColor(Color.TRANSPARENT);
        ((ViewGroup) (view.getParent().getParent().getParent().getParent().getParent())).setBackgroundColor(Color.TRANSPARENT);
        ((TextView) view.findViewById(R.id.tv_price)).setText(String.format("%s CNY", CoinUtil.keepRMB(price)));
        ((TextView) view.findViewById(R.id.tv_amount)).setText(String.format("%s USDT", CoinUtil.keepUSDT(num)));
        String money = CoinUtil.keepRMB(new BigDecimal(num).multiply(new BigDecimal(price)).toPlainString());
        ((TextView) view.findViewById(R.id.tv_money)).setText(String.format("%s CNY", CoinUtil.keepUSDT(money)));
        ((TextView) view.findViewById(R.id.tv_price_left)).setText(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil15_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        ((TextView) view.findViewById(R.id.tv_amount_left)).setText(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil7_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        ((TextView) view.findViewById(R.id.tv_money_left)).setText(String.format(App.INSTANCE.getString(R.string.fabi_tipFabiUtil16_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        EditText et_pwd = view.findViewById(R.id.et_pwd);
        ClickUtil.click(view.findViewById(R.id.tvCancel), () -> {
            dialog.dismiss();
        });
        ClickUtil.click(view.findViewById(R.id.tvSure), () -> {
            if (TextUtils.isEmpty(et_pwd.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil14_h));
                return;
            }
            if (!CheckUtil.isPayPwd(et_pwd.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil17_h));
                return;
            }
            dialog.dismiss();
            onInputList.onSure(et_pwd.getText().toString());
        });
        return dialog;
    }

    public static void showQR(Activity activity, String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        View view = View.inflate(activity, R.layout.fabi_dialog_erweima, null);
        ImageView ivQR = view.findViewById(R.id.ivQRCode);
        TextView tvQR = view.findViewById(R.id.tvContent);
        builder.setView(view);
        builder.setCancelable(true);
        AlertDialog qrDialog = builder.create();

        ImageUtil.setImage(url, ivQR);
        ClickUtil.click(tvQR, () -> {
            new RxPermissions(activity).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(isGrant -> {
                        if (isGrant) {
                            if (!ImgUtil.saveImageToGallery(activity, ivQR)) {
                                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil18_h));
                            }
                        } else {
                            PermissionTipUtil.tip(activity, App.INSTANCE.getString(R.string.fabi_tipFabiUtil19_h));
                        }
                    });
        });
        tvQR.setText(App.INSTANCE.getString(R.string.fabi_tipFabiUtil20_h));
        qrDialog.show();
    }

    public static BottomSheetDialog getPay(Activity activity, OnInputList onInputList) {
        BottomSheetDialog codeDialog = new BottomSheetDialog(activity);
        View dialogView = LayoutInflater.from(activity)
                .inflate(R.layout.fabi_bottom_sheet_check_code, null);
        EditText mPayPwdEditText = dialogView.findViewById(R.id.et_code);
        ClickUtil.click(dialogView.findViewById(R.id.tv_cancel), codeDialog::dismiss);
        Button mSubmit = dialogView.findViewById(R.id.bt_submit);
        codeDialog.setContentView(dialogView);


        ClickUtil.click(mSubmit, () -> { //提交修改

            String pwd = mPayPwdEditText.getText().toString().trim();
            if (TextUtils.isEmpty(pwd)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil21_h));
                return;
            }
            if (!CheckUtil.isPayPwd(pwd)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_tipFabiUtil17_h));
                return;
            }
            onInputList.onSure(pwd);

        });
        return codeDialog;
    }

    public interface OnInputList {
        void onSure(String... str);

    }


    /**
     * 根据法币计价和出售数量计算总的数量与价格
     */
    private static String calculateAll(boolean isPrice, String price, String leftNum, String maxLimit) {

        String num = "0.0000";
        BigDecimal allMoney = new BigDecimal(leftNum).multiply(new BigDecimal(price));//最多购买金额
        BigDecimal allNum = new BigDecimal(maxLimit).divide(new BigDecimal(price), 8, BigDecimal.ROUND_DOWN);

        if (isPrice) {
            if (!TextUtils.isEmpty(price)) {
                double buyPrice = Math.min(Double.valueOf(maxLimit), allMoney.doubleValue());
                return CoinUtil.keepRMB(buyPrice);
            }
        } else {
            if (!TextUtils.isEmpty(price)) {
                double buyNum = Math.min(allNum.doubleValue(), Double.valueOf(leftNum));
                return CoinUtil.keepUSDT(buyNum);
            }
        }
        return num;
    }
}
